import fs from 'fs';
import path from 'path';
import { SSHConfig } from '../types';

const CONFIG_FILE = path.join(process.cwd(), 'servers.json');

export interface ServerProfile {
  id: string;
  name: string;
  description?: string;
  config: SSHConfig;
  createdAt: Date;
  lastUsed?: Date;
}

export class ServerConfigManager {
  private profiles: ServerProfile[] = [];

  constructor() {
    this.loadProfiles();
  }

  private loadProfiles(): void {
    try {
      if (fs.existsSync(CONFIG_FILE)) {
        const data = fs.readFileSync(CONFIG_FILE, 'utf8');
        const parsed = JSON.parse(data);
        this.profiles = parsed.map((p: any) => ({
          ...p,
          createdAt: new Date(p.createdAt),
          lastUsed: p.lastUsed ? new Date(p.lastUsed) : undefined
        }));
      }
    } catch (error) {
      console.error('加载服务器配置失败:', error);
      this.profiles = [];
    }
  }

  private saveProfiles(): void {
    try {
      fs.writeFileSync(CONFIG_FILE, JSON.stringify(this.profiles, null, 2));
    } catch (error) {
      console.error('保存服务器配置失败:', error);
    }
  }

  addProfile(name: string, config: SSHConfig, description?: string): string {
    const id = Date.now().toString();
    const profile: ServerProfile = {
      id,
      name,
      description,
      config,
      createdAt: new Date()
    };

    this.profiles.push(profile);
    this.saveProfiles();
    return id;
  }

  getProfiles(): ServerProfile[] {
    return [...this.profiles].sort((a, b) => {
      // 按最后使用时间排序，未使用的按创建时间排序
      if (a.lastUsed && b.lastUsed) {
        return b.lastUsed.getTime() - a.lastUsed.getTime();
      }
      if (a.lastUsed && !b.lastUsed) return -1;
      if (!a.lastUsed && b.lastUsed) return 1;
      return b.createdAt.getTime() - a.createdAt.getTime();
    });
  }

  getProfile(id: string): ServerProfile | undefined {
    return this.profiles.find(p => p.id === id);
  }

  updateLastUsed(id: string): void {
    const profile = this.profiles.find(p => p.id === id);
    if (profile) {
      profile.lastUsed = new Date();
      this.saveProfiles();
    }
  }

  updateProfile(id: string, updates: Partial<ServerProfile>): boolean {
    const index = this.profiles.findIndex(p => p.id === id);
    if (index !== -1) {
      this.profiles[index] = { ...this.profiles[index], ...updates };
      this.saveProfiles();
      return true;
    }
    return false;
  }

  deleteProfile(id: string): boolean {
    const index = this.profiles.findIndex(p => p.id === id);
    if (index !== -1) {
      this.profiles.splice(index, 1);
      this.saveProfiles();
      return true;
    }
    return false;
  }

  getFormattedList(): Array<{ name: string; value: string; description?: string }> {
    const profiles = this.getProfiles();

    const choices = profiles.map(profile => {
      const lastUsed = profile.lastUsed
        ? ` (上次使用: ${profile.lastUsed.toLocaleDateString()})`
        : '';

      return {
        name: `${profile.name} - ${profile.config.host}:${profile.config.port}${lastUsed}`,
        value: profile.id,
        description: profile.description
      };
    });

    // 添加新建选项
    choices.push({
      name: '+ 添加新服务器',
      value: 'new',
      description: undefined
    });

    return choices;
  }
}